package com.gjy.service.es.service.impl;

import com.gjy.service.es.service.AggregationService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-07-03 14:58:57
 */
@Service
public class AggregationServiceImpl implements AggregationService {

    private static final Logger log = LoggerFactory.getLogger(AggregationServiceImpl.class);

    @Resource
    private RestHighLevelClient esClient;

    @Override
    public void term(String index, String term, String value) throws Exception {
        SearchRequest request = new SearchRequest(index);
        SearchSourceBuilder builder = new SearchSourceBuilder();

        builder.aggregation(AggregationBuilders.terms(value).field(term));

        request.source(builder);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        Aggregations aggregations = response.getAggregations();
        ParsedStringTerms t = aggregations.get(value);
        for (Terms.Bucket bucket : t.getBuckets()) {
            long docCount = bucket.getDocCount();
            String keyAsString = bucket.getKeyAsString();
            log.info("docCount={}, key={}", docCount, keyAsString);
        }
    }
}
